#include "App_mqtt.h"




#define MQTTTAG "MQTT"

// MQTT 初始化完成信号量（二值信号量）
SemaphoreHandle_t mqtt_initialized_sem = NULL;

esp_mqtt_client_handle_t client;    //mqtt客户端句柄


//mqtt的事件处理函数       
static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data)
{
    //输出事件的基本信息
    ESP_LOGD(MQTTTAG, "Event dispatched from event loop base=%s, event_id=%" PRIi32, base, event_id);
    esp_mqtt_event_handle_t event = event_data;
    
    switch ((esp_mqtt_event_id_t)event_id) {
    case MQTT_EVENT_CONNECTED:  
        ESP_LOGI(MQTTTAG, "MQTT_EVENT_CONNECTED");  //输出连接成功的信息
        
        xSemaphoreGive(mqtt_initialized_sem); //释放MQTT连接成功信号量

        //msg_id = esp_mqtt_client_subscribe(client, OneNET_Subscribe_Topic, 0);   //订阅主题，返回值是消息ID
        break;

    case MQTT_EVENT_DISCONNECTED:   
        ESP_LOGI(MQTTTAG, "MQTT_EVENT_DISCONNECTED");   //输出断开连接的信息
        break;
    case MQTT_EVENT_SUBSCRIBED:
        ESP_LOGI(MQTTTAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);   //输出订阅成功的信息
        break;
    case MQTT_EVENT_UNSUBSCRIBED:
        ESP_LOGI(MQTTTAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id); //输出取消订阅成功的信息
        break;
    case MQTT_EVENT_PUBLISHED:
        ESP_LOGI(MQTTTAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);    //输出发布成功的信息
        break;

    case MQTT_EVENT_DATA:
        ESP_LOGI(MQTTTAG, "MQTT_EVENT_DATA");       //输出接收到数据的信息
        ESP_LOGI(MQTTTAG, "TOPIC=%.*s", event->topic_len, event->topic);    //输出接收到的主题
        ESP_LOGI(MQTTTAG, "DATA=%.*s", event->data_len, event->data);       //输出接收到的数据
        break;

        
    case MQTT_EVENT_ERROR:
        ESP_LOGI(MQTTTAG, "MQTT_EVENT_ERROR");  //输出错误信息
        break;
    default:
        ESP_LOGI(MQTTTAG, "Other event id:%d", event->event_id);    //输出其他事件的信息
        break;
    }
}



void MQTT_Init(void)
{
    if (xSemaphoreTake(wifi_connected_sem, portMAX_DELAY) == pdPASS){ //等待WiFi连接成功信号量
        
     
        mqtt_initialized_sem = xSemaphoreCreateBinary(); //创建二值信号量
        ESP_LOGI("MQTT", "WIFI连接成功，正在MQTT 初始化...");

        //mqtt连接配置
        esp_mqtt_client_config_t mqtt_cfg = {
            .session.protocol_ver = MQTT_PROTOCOL_V_3_1_1, //mqtt协议版本
            .broker.address.uri = CONFIG_BROKER_URL,
            .broker.address.port = CONFIG_BROKER_PORT, //mqtt服务器端口 
            //.broker.address.transport = MQTT_TRANSPORT_OVER_TCP, //mqtt传输方式
            .credentials.client_id = CONFIG_CONNECT_ID, //连接ID（设备名称）
            .credentials.username = CONFIG_USER_NAME, //用户名称（产品ID）
            .credentials.authentication.password = CONFIG_PASSWORD, //密码（软件生成）
        };

        //初始化MQTT客户端，返回值是MQTT客户端句柄。
        client = esp_mqtt_client_init(&mqtt_cfg);   
        //注册MQTT事件处理函数
        esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, client); //注册MQTT事件处理函数，返回值是MQTT客户端句柄。
        //启动MQTT客户端
        esp_mqtt_client_start(client);

    }
}
